import React, { useEffect, useRef, useState } from "react";
import { ArrowLeft, Setting } from "@nutui/icons-react";
import { Success, Cross } from "@react-vant/icons";
import { Button, Cell } from "react-vant";
import { useNavigate } from "react-router-dom";
import { Popover, Toast } from "antd-mobile";
import axios from "axios";
import "../styles/Face.less";

export default function Facelogin() {
  const [currentImage, setCurrentImage] = useState("sxt2.png");
  const [cameraOn, setCameraOn] = useState(false);
  const videoRef = useRef(null);
  const navigate = useNavigate();
  const [flag, setFlag] = useState(false);
  const [flag1, setFlag1] = useState(false);

  const canvasRef = useRef(null);
  const [capturedImages, setCapturedImages] = useState([]);

  const startCamera = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ video: true });
      videoRef.current.srcObject = stream;
      setCameraOn(true);
    } catch (error) {
      console.log("访问摄像头出错：", error);
    }
  };

  const closeMedia = () => {
    if (videoRef.current.srcObject) {
      const stream = videoRef.current.srcObject;
      const tracks = stream.getTracks();
      tracks.forEach((track) => {
        track.stop();
      });
      videoRef.current.srcObject = null;
      setCameraOn(false);
    }
  };

  useEffect(() => {
    startCamera();
  }, []);

  const toggleCameraAndImage = () => {
    if (cameraOn) {
      setCurrentImage("sxt1.png");
      closeMedia();
    } else {
      setCurrentImage("sxt2.png");
      startCamera();
    }
  };

  const capture = () => {
    if (!canvasRef.current || !videoRef.current) return;

    const canvas = canvasRef.current;
    const context = canvas.getContext("2d");
    context.drawImage(videoRef.current, 0, 0, canvas.width, canvas.height);
    const imageSrc = canvas.toDataURL("image/jpeg");
    setCapturedImages([...capturedImages, imageSrc]);
    submitImages(imageSrc);
    setFlag(false);
    setFlag1(false);
  };

  const submitImages = async (img) => {
    try {
      setFlag(false);
      setFlag1(false);
      const res = await axios.post("http://127.0.0.1:3000/jxy/faceLogin", {
        b64: img,
      });
      if (res.data.code === 200) {
        setFlag(true);
        setTimeout(async () => {
          setFlag(false);
          let data = await axios.post(`http://127.0.0.1:3000/jxy/loginface?face_id=${res.data.doc.Results[0].Candidates[0].PersonId}`)
          if (data.data.code == 200) {
            sessionStorage.setItem('token', data.data.token)
            sessionStorage.setItem('user', JSON.stringify(data.data.user1))
            navigate('/login')
          }
        }, 1500);
      }
      if (res.data.code === 401) {
        Toast.show({
          icon: "success",
          content: "登入失败",
        });
        setFlag1(true);
      }
    } catch (error) {
      Toast.show({
        icon: "success",
        content: "登入失败",
      });
      console.log("提交图像出错", error);
      setFlag1(true);
    }
  };

  return (
    <div>
      <div className="face_header">
        <p
          style={{ marginTop: "0.1rem", width: "15%" }}
          onClick={() => navigate("/login")}
        >
          <ArrowLeft />
        </p>
        <p style={{ width: "70%", textAlign: "center" }}>人脸验证</p>
        <p style={{ animation: "bounce 1s linear infinite", style: "15%" }}>
          <img
            src="/register.png"
            alt=""
            style={{ width: "0.63rem" }}
            className="bounce"
          />
        </p>
      </div>
      <p>
        <span
          style={{
            fontSize: "14px",
            paddingLeft: "35px",
            color: "red",
            display: flag1 ? "block" : "none",
          }}
        >
          请选择使用验证码或重新进行登录
        </span>
      </p>
      <div style={{ marginTop: "70px", height: "auto", position: "relative" }}>
        <Cell>
          <div className="jxy_face_kl">
            <video ref={videoRef} autoPlay muted></video>
            <canvas ref={canvasRef} style={{ display: "none" }}></canvas>
          </div>
        </Cell>
        <Button
          onClick={capture}
          style={{ width: "50%", margin: "50px auto" }}
          color="linear-gradient(to right, rgb(78,115,223), rgb(2,167,240))"
          type="primary"
          block
          round
        >
          开始认证
        </Button>
        <div className="jxy_face_mask_err" style={{ display: flag1 ? "block" : "none" }}>
          <Cross
            className="jxy_face_icon1"
            style={{ color: "white", fontSize: "60px" }}
          />
        </div>
        <div
          className="jxy_face_mask_success"
          style={{ display: flag ? "block" : "none" }}
        >
          <Success
            className="jxy_face_icon1"
            style={{ color: "white", fontSize: "60px" }}
          />
        </div>
      </div>

      <Popover
        content={
          <>
            <img
              src={currentImage}
              style={{ width: "0.45rem", height: "0.35rem" }}
              alt=""
              onClick={() => toggleCameraAndImage()}
            />
          </>
        }
        trigger="click"
        placement="left-end"
      >
        <div
          style={{
            width: "35px",
            height: "35px",
            position: "fixed",
            bottom: "70px",
            right: "20px",
            border: "1px solid #d5d5d5",
            borderRadius: "50px",
            textAlign: "center",
            lineHeight: "42px",
          }}
        >
          <Setting />
        </div>
      </Popover>
    </div>
  );
}